import { useState, useEffect } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Badge } from '@/components/ui/badge'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { 
  FileText, 
  Download, 
  FileSpreadsheet,
  BarChart3,
  TrendingUp,
  Clock,
  CheckCircle,
  AlertCircle,
  Plus
} from 'lucide-react'
import { toast } from 'sonner'
import apiService from '../services/api'

export default function ReportGeneration() {
  const [reports, setReports] = useState([])
  const [tasks, setTasks] = useState([])
  const [loading, setLoading] = useState(false)
  const [generating, setGenerating] = useState(false)
  const [selectedTask, setSelectedTask] = useState('')
  const [selectedTemplate, setSelectedTemplate] = useState('product_forecast')

  const templates = [
    {
      id: 'product_forecast',
      name: '重点产品销售预测模板',
      description: '包含销售量、单价、成本等详细预测数据',
      icon: <TrendingUp className="h-5 w-5" />
    },
    {
      id: 'historical_data',
      name: '重点产品历史数据模板',
      description: '历史经营数据汇总和趋势分析',
      icon: <BarChart3 className="h-5 w-5" />
    },
    {
      id: 'comprehensive',
      name: '经营指标历史数据+预测模板',
      description: '集团层面综合经营指标分析',
      icon: <FileSpreadsheet className="h-5 w-5" />
    }
  ]

  useEffect(() => {
    loadReports()
    loadCompletedTasks()
  }, [])

  const loadReports = async () => {
    try {
      setLoading(true)
      const response = await apiService.getReports({ page: 1, page_size: 50 })
      const items = response.data?.items || []
      setReports(items)
    } catch (error) {
      console.error('加载报表列表失败:', error)
      // 使用模拟数据作为后备
      setReports([
        {
          id: '1',
          filename: 'product_forecast_20240826_143022.xlsx',
          template_type: 'product_forecast',
          task_name: '2026年医药产品预测',
          file_size: '2.34 MB',
          generated_at: '2024-08-26T14:30:22Z',
          status: 'completed'
        },
        {
          id: '2',
          filename: 'historical_data_20240826_120015.xlsx',
          template_type: 'historical_data',
          task_name: '历史数据汇总',
          file_size: '1.87 MB',
          generated_at: '2024-08-26T12:00:15Z',
          status: 'completed'
        }
      ])
    } finally {
      setLoading(false)
    }
  }

  const loadCompletedTasks = async () => {
    try {
      const response = await apiService.getPredictionTasks({ 
        page: 1, 
        page_size: 50,
        status: 'completed'
      })
      const items = response.data?.items || []
      setTasks(items.filter(task => task.status === 'completed'))
    } catch (error) {
      console.error('加载已完成任务失败:', error)
      // 使用模拟数据作为后备
      setTasks([
        {
          task_id: '1',
          task_name: '2026年医药产品预测',
          status: 'completed',
          created_at: '2024-08-26T10:00:00Z'
        },
        {
          task_id: '2',
          task_name: '重点产品销售预测',
          status: 'completed',
          created_at: '2024-08-26T09:00:00Z'
        }
      ])
    }
  }

  const handleGenerateReport = async () => {
    if (!selectedTask) {
      toast.error('请选择一个已完成的任务')
      return
    }

    try {
      setGenerating(true)
      const response = await apiService.generateReport({
        template_type: selectedTemplate,
        task_id: selectedTask,
        options: {
          include_charts: true,
          format: 'xlsx'
        }
      })

      const newReport = response.data
      toast.success('报表生成成功')
      
      // 添加到报表列表
      setReports(prev => [newReport, ...prev])
      
      // 重置选择
      setSelectedTask('')
      setSelectedTemplate('product_forecast')
    } catch (error) {
      console.error('生成报表失败:', error)
      toast.error(error.message || '生成报表失败')
    } finally {
      setGenerating(false)
    }
  }

  const handleDownloadReport = (filename) => {
    try {
      apiService.downloadReport(filename)
      toast.success('开始下载报表')
    } catch (error) {
      console.error('下载报表失败:', error)
      toast.error('下载报表失败')
    }
  }

  const getStatusIcon = (status) => {
    switch (status) {
      case 'completed':
        return <CheckCircle className="h-4 w-4 text-green-500" />
      case 'generating':
        return <Clock className="h-4 w-4 text-blue-500" />
      case 'failed':
        return <AlertCircle className="h-4 w-4 text-red-500" />
      default:
        return <Clock className="h-4 w-4 text-gray-500" />
    }
  }

  const getStatusBadge = (status) => {
    const variants = {
      completed: 'default',
      generating: 'secondary',
      failed: 'destructive'
    }
    const labels = {
      completed: '已完成',
      generating: '生成中',
      failed: '失败'
    }
    return <Badge variant={variants[status]}>{labels[status]}</Badge>
  }

  const formatDate = (dateString) => {
    if (!dateString) return '-'
    return new Date(dateString).toLocaleString('zh-CN')
  }

  const getTemplateInfo = (templateType) => {
    return templates.find(t => t.id === templateType) || templates[0]
  }

  return (
    <div className="p-6 space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-gray-900">报表生成</h1>
          <p className="text-gray-600 mt-1">生成和管理预测分析报表</p>
        </div>
        <Button onClick={handleGenerateReport} disabled={generating}>
          {generating ? (
            <>
              <Clock className="h-4 w-4 mr-2 animate-spin" />
              生成中...
            </>
          ) : (
            <>
              <Plus className="h-4 w-4 mr-2" />
              生成报表
            </>
          )}
        </Button>
      </div>

      {/* Generate Report Section */}
      <Card>
        <CardHeader>
          <CardTitle>生成新报表</CardTitle>
          <CardDescription>
            选择模板和任务生成专业的Excel报表
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-6">
          {/* Template Selection */}
          <div className="space-y-3">
            <Label>选择报表模板</Label>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              {templates.map((template) => (
                <div
                  key={template.id}
                  className={`p-4 border rounded-lg cursor-pointer transition-colors ${
                    selectedTemplate === template.id
                      ? 'border-blue-500 bg-blue-50'
                      : 'border-gray-200 hover:border-gray-300'
                  }`}
                  onClick={() => setSelectedTemplate(template.id)}
                >
                  <div className="flex items-start space-x-3">
                    <div className="text-blue-500 mt-1">
                      {template.icon}
                    </div>
                    <div className="flex-1">
                      <h3 className="font-medium text-gray-900">{template.name}</h3>
                      <p className="text-sm text-gray-500 mt-1">{template.description}</p>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* Task Selection */}
          <div className="space-y-2">
            <Label htmlFor="task-select">选择预测任务</Label>
            <Select value={selectedTask} onValueChange={setSelectedTask}>
              <SelectTrigger>
                <SelectValue placeholder="选择一个已完成的预测任务" />
              </SelectTrigger>
              <SelectContent>
                {tasks.map((task) => (
                  <SelectItem key={task.task_id} value={task.task_id}>
                    {task.task_name} - {formatDate(task.created_at)}
                  </SelectItem>
                ))}
                {tasks.length === 0 && (
                  <SelectItem value="" disabled>
                    暂无已完成的任务
                  </SelectItem>
                )}
              </SelectContent>
            </Select>
          </div>
        </CardContent>
      </Card>

      {/* Reports List */}
      <Card>
        <CardHeader>
          <CardTitle>报表列表</CardTitle>
          <CardDescription>
            查看和下载已生成的报表文件
          </CardDescription>
        </CardHeader>
        <CardContent>
          {loading ? (
            <div className="text-center py-8 text-gray-500">
              加载中...
            </div>
          ) : (
            <div className="space-y-4">
              {reports.map((report) => {
                const templateInfo = getTemplateInfo(report.template_type)
                return (
                  <div key={report.id} className="flex items-center justify-between p-4 border rounded-lg">
                    <div className="flex items-center space-x-4">
                      <div className="text-blue-500">
                        {templateInfo.icon}
                      </div>
                      <div>
                        <h3 className="font-medium text-gray-900">
                          {report.filename || report.task_name}
                        </h3>
                        <p className="text-sm text-gray-500">
                          {templateInfo.name} • {report.file_size} • {formatDate(report.generated_at)}
                        </p>
                      </div>
                    </div>
                    <div className="flex items-center space-x-3">
                      {getStatusIcon(report.status)}
                      {getStatusBadge(report.status)}
                      {report.status === 'completed' && (
                        <Button 
                          variant="outline" 
                          size="sm"
                          onClick={() => handleDownloadReport(report.filename)}
                        >
                          <Download className="h-4 w-4 mr-2" />
                          下载
                        </Button>
                      )}
                    </div>
                  </div>
                )
              })}
              {reports.length === 0 && (
                <div className="text-center py-8 text-gray-500">
                  暂无报表
                </div>
              )}
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  )
}

